package org.robot.scm.platform.server.handler;

import cn.hutool.core.io.FileUtil;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.pojos.config.BaseConfig;

@Slf4j
@NoArgsConstructor
public class FileHttpHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/file";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("GET")) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }
        String path = exchange.getRequestURI().getPath();
        File file = new File("assets" + path.replace("/file", "/telegram"));
        if (!file.exists()) {
            sendFailureResponse(exchange, "404 NOT FOUND");
            return;
        }
        exchange.getResponseHeaders().add("Content-Type", getMimeType(file) + "; charset=UTF-8");
        exchange.sendResponseHeaders(200, file.length());
        try (OutputStream responseBody = exchange.getResponseBody(); FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                responseBody.write(buffer, 0, read);
            }
        }
        exchange.close();
    }

    /**
     * 根据文件扩展名获取MIME类型。
     */
    private String getMimeType(File file) {
        switch (FileUtil.extName(file).toLowerCase()) {
            case "html":
                return "text/html";
            case "css":
                return "text/css";
            case "js":
                return "application/javascript";
            case "png":
                return "image/png";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "gif":
                return "image/gif";
            case "pdf":
                return "application/pdf";
            case "sql":
            case "txt":
            case "file":
                return "text/plain";
            case "doc":
            case "docx":
                return "application/msword";
            case "ppt":
            case "pptx":
                return "application/vnd.ms-powerpoint";
            case "xls":
            case "xlsx":
                return "application/vnd.ms-excel";
            case "xml":
                return "application/xml";
            case "zip":
                return "application/zip";
            case "mp3":
                return "audio/mpeg";
            case "mp4":
                return "video/mp4";
            default:
                return "application/octet-stream";
        }
    }
}
